package com.tongcao.cn.filter;

import com.tongcao.cn.manager.HttpManager;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author:tongcao
 * @Date:2018/8/23 17:35
 * Description:springmvc的入口是dispatcherServlet类，同时看HanderInterceptor处理流程，重点是HanderInterceptor是通过dispatcherServlet来控制访问的，而filter和dispatcherServlet在web.xml中是平级的，并且filter是由web的容器管理，也就是说filter不在springmvc容器中，而HanderIntercptor在spring容器中，这是在使用过程中最主要的一个区别，所以你可以在interceptor中注入bean而filter中不能注入。
 */
@WebFilter(urlPatterns = "/*", filterName = "aFilter")
@Order(value = 1)
public class AFilter implements Filter {

    @Resource
    HttpManager httpManager;
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("/main/excludefilter", "/login", "/logout", "/register")));


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
            //此处空指针
//            httpManager.doGet("www.baidu.com");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
//        System.out.println("*************我是AFilter**********" + path);
        filterChain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}
